package org.jks.util;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.jks.model.Msg;
import org.jks.model.MsgTask;
import org.jks.service.MsgTaskService;
import org.jks.sms.Sms;

public class MessageUtil {
	private MsgTaskService msgTaskService;
	private static List<MsgTask> msgTasks = new ArrayList<MsgTask>();
	private static ScheduledExecutorService service;

	public MessageUtil(MsgTaskService msgTaskService) {
		service = Executors.newScheduledThreadPool(1);
		this.msgTaskService = msgTaskService;
	}

	public synchronized static void add(List<MsgTask> tasks) {
		synchronized(msgTasks){
			msgTasks.addAll(tasks);
		}
	}

	public synchronized static void add(MsgTask task) {
		synchronized(msgTasks){
			msgTasks.add(task);
		}
	}

	public void start() {
		service.scheduleAtFixedRate(new Runnable() {
			public void run() {
				synchronized(msgTasks){
					if (msgTasks.size() > 0) {
						for(MsgTask task : msgTasks){
							List<Msg> msgs = task.getMsgs();
							if(msgs != null && msgs.size() > 0){
								for(Msg msg: msgs){
									if(msg.getUser() != null && msg.getUser().getContactNumber() != null){
										Sms.sendMessage(msg.getUser().getContactNumber(), task.getNotifyContent());
									}
								}
							}
							msgTaskService.delete(task);
						}
						msgTasks.clear();
					}
				}
			}
		}, 100, 200, TimeUnit.MILLISECONDS);
	}

	public void stop() {
		service.shutdown();
	}
}
